<template>
  <div class="processor-container">
    <div class="action-bar">
      <el-button 
        type="primary" 
        @click="loadCourseDetails"
        :disabled="selectedCourses.length === 0"
        :loading="loadingDetails"
      >
        📥 加载课程详情
      </el-button>
      
      <div class="process-info">
        <el-badge :value="selectedHomeworksCount" :max="99" type="danger">
          <el-button
            type="success"
            :disabled="!canProcess"
            :loading="processing"
            @click="startProcessing"
          >
            🚀 {{ buttonText }}
          </el-button>
        </el-badge>
        <span class="hint-text" v-show="selectedHomeworksCount">包含 {{ selectedHomeworksCount }} 个待处理作业</span>
      </div>
    </div>

    <el-table 
      :data="courseDetails" 
      border 
      height="calc(100vh - 280px)"
      style="width: 100%; margin-top: 15px;"
      @selection-change="handleCourseSelect"
      row-key="id"
      v-loading="loadingDetails"
      :row-class-name="rowClassName"
    >
      <el-table-column 
        type="selection" 
        width="55" 
        :selectable="selectable"
        reserve-selection
      />
      <el-table-column prop="homeWorkName" label="课程名称" width="320">
        <template #header>
          <span class="table-header">📚 课程名称</span>
        </template>
      </el-table-column>
      <el-table-column label="最高分" width="140" align="center">
        <template #header>
          <span class="table-header">🎯 最高分</span>
        </template>
        <template #default="{ row }">
          <el-tag 
            :type="row.maxScore >= 100 ? 'success' : 'warning'" 
            size="small"
            class="score-tag"
          >
            {{ row.maxScore }} 分
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120" align="center">
        <template #header>
          <span class="table-header">📊 状态</span>
        </template>
        <template #default="{ row }">
          <el-icon :color="row.maxScore >= 100 ? '#67C23A' : '#E6A23C'">
            <component :is="row.maxScore >= 100 ? CircleCheck : Clock" />
          </el-icon>
          <span class="status-text">
            {{ row.maxScore >= 100 ? '已完成' : '待处理' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template #header>
          <span class="table-header">⚙️ 操作</span>
        </template>
        <template #default="{ row }">
          <el-tooltip content="查看详情" placement="top">
            <el-button 
              link 
              type="primary" 
              size="small" 
              @click="showDetail(row)"
            >
              <el-icon><View /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { CircleCheck, Clock, View } from '@element-plus/icons-vue'

// 组件属性定义
const props = defineProps({
  token: String,                // 用户访问令牌
  selectedCourses: {            // 选中的课程列表
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update-tasks'])

// 状态变量定义
const processing = ref(false)           // 作业处理状态
const loadingDetails = ref(false)       // 课程详情加载状态
const courseDetails = ref([])           // 作业详情列表
const selectedCourseIds = ref([])       // 选中的作业ID列表
const API_BASE = '/jxjyzx'             // API基础路径
const PROCESS_DELAY = 800              // 处理间隔时间(ms)
const SUBMIT_DELAY = 1500              // 提交间隔时间(ms)

// 计算属性：判断是否可以开始处理作业
const canProcess = computed(() => 
  selectedCourseIds.value.length > 0 && !!props.token && !processing.value
)

// 计算属性：获取待处理作业数量
const selectedHomeworksCount = computed(() => 
  courseDetails.value.filter(c => 
    selectedCourseIds.value.includes(c.id) && c.maxScore < 100
  ).length
)

// 计算属性：处理按钮文本
const buttonText = computed(() => 
  processing.value ? '处理中...' : '开始处理'
)

// API请求统一封装处理
const fetchAPI = async (url, options = {}) => {
  const headers = {
    'Content-Type': 'application/json',
    'access-token': props.token,
    ...options.headers
  }

  const response = await fetch(`${API_BASE}${url}`, {
    ...options,
    headers,
    body: options.body ? JSON.stringify(options.body) : null
  })

  if (!response.ok) {
    throw new Error(`HTTP错误 ${response.status}`)
  }
  
  return response.json()
}

// 处理单个作业的核心逻辑
const processHomework = async (courseOpenId, homeWorkId) => {
  try {
    // 1. 获取作业详情
    const detail = await fetchAPI('/study/detail', {
      method: 'POST',
      body: { courseOpenId, homeWorkId }
    })
    
    const homeworkData = detail.data
    if (!homeworkData) return

    // 2. 获取作业试卷信息
    const paperRes = await fetchAPI(`/study/getStuHomeWorkPaper?workId=${homeWorkId}`)
    const paper = paperRes.data.stuPaperMongo
    const bigQuestion = paper.bigQuestions[0]

    // 3. 获取答案列表
    let answerList = []
    const hasHistory = homeworkData.stuHistoryList?.length > 0

    if (hasHistory) {
      // 3.1 如果有历史记录，直接获取历史答案
      const history = await fetchAPI(`/study/getHistory?id=${homeworkData.stuHistoryList[0].id}`)
      answerList = history.data.paperMongo.bigQuestions[0].stuQuestions.map(q => q.answer)
    } else {
      // 3.2 无历史记录，先提交空白试卷
      await fetchAPI('/study/homeWorkSave', {
        method: 'POST',
        body: {
          courseOpenId,
          isSubmitWithoutAll: 1,
          paperId: paper.id,
          type: "0"
        }
      })
      await new Promise(resolve => setTimeout(resolve, SUBMIT_DELAY))

      // 3.3 重新获取作业详情和答案
      const newDetail = await fetchAPI('/study/detail', {
        method: 'POST',
        body: { courseOpenId, homeWorkId }
      })
      const newHomeworkData = newDetail.data

      if (newHomeworkData.stuHistoryList?.length > 0) {
        const newHistory = await fetchAPI(`/study/getHistory?id=${newHomeworkData.stuHistoryList[0].id}`)
        answerList = newHistory.data.paperMongo.bigQuestions[0].stuQuestions.map(q => q.answer)
      } else {
        throw new Error('答案获取失败，请尝试手动提交')
      }
    }

    // 4. 并行提交所有题目答案
    await Promise.all(
      bigQuestion.stuQuestions.map((question, index) => 
        fetchAPI('/submit/doExamPaperJudgment', {
          method: 'POST',
          body: {
            answer: answerList[index] || " ",
            bigQuestionId: bigQuestion.id,
            online: 1,
            paperId: paper.id,
            questionId: question.id
          }
        })
      )
    )

    // 5. 最终提交完整试卷
    await new Promise(resolve => setTimeout(resolve, SUBMIT_DELAY))
    await fetchAPI('/study/homeWorkSave', {
      method: 'POST',
      body: {
        courseOpenId,
        isSubmitWithoutAll: 0,
        paperId: paper.id,
        type: "0"
      }
    })

    // 6. 更新本地作业状态
    const targetIndex = courseDetails.value.findIndex(c => c.id === `${courseOpenId}_${homeWorkId}`)
    if (targetIndex > -1) {
      courseDetails.value[targetIndex].maxScore = 100
      emit('update-tasks', [])
    }

  } catch (error) {
    ElMessage.error(`作业处理失败: ${error.message}`)
    throw error
  }
}

// 批量处理选中的作业
const startProcessing = async () => {
  processing.value = true
  try {
    // 筛选未完成的作业
    const validSelections = courseDetails.value
      .filter(c => selectedCourseIds.value.includes(c.id) && c.maxScore < 100)

    // 并行处理所有选中的作业
    const results = await Promise.allSettled(
      validSelections.map(selection => {
        const [courseId, homeworkId] = selection.id.split('_')
        return processHomework(courseId, homeworkId)
      })
    )

    // 处理结果统计和提示
    const failedItems = results.filter(r => r.status === 'rejected')
    if (failedItems.length > 0) {
      ElMessage.error(`有 ${failedItems.length} 个作业处理失败`)
    }

    if (failedItems.length < results.length) {
      ElNotification.success({
        title: '处理完成',
        message: `成功处理 ${results.length - failedItems.length} 个作业`,
        duration: 3000
      })
    }

  } catch (error) {
    ElMessage.error('处理过程中出现意外错误')
  } finally {
    processing.value = false
    emit('update-tasks', [])
  }
}

// 加载课程作业详情列表
const loadCourseDetails = async () => {
  loadingDetails.value = true
  courseDetails.value = []
  try {
    // 并行加载所有选中课程的作业列表
    const details = await Promise.all(
      props.selectedCourses.map(async course => {
        try {
          const data = await fetchAPI('/study/getPlanHomeWork', {
            method: 'POST',
            body: {
              courseOpenId: course.id,
              pageSize: 100
            }
          })
          // 为每个作业添加唯一标识
          return data.data?.list?.map(item => ({
            ...item,
            id: `${course.id}_${item.id}`
          })) || []
        } catch (error) {
          ElMessage.error(`课程 ${course.name} 加载失败`)
          return []
        }
      })
    )
    courseDetails.value = details.flat()
    ElNotification.success({
      title: '加载成功',
      message: `共加载 ${courseDetails.value.length} 个作业项`,
      duration: 2000
    })
    emit('update-tasks', [])
  } catch (error) {
    ElMessage.error('课程详情加载失败: ' + error.message)
  } finally {
    loadingDetails.value = false
  }
}

// 表格选择变化处理
const handleCourseSelect = (selection) => {
  selectedCourseIds.value = selection.map(c => c.id)
  emit('update-tasks', [])
}

// 判断作业是否可选（分数小于100分的可选）
const selectable = ({ maxScore }) => maxScore < 100

// 设置已完成作业的行样式
const rowClassName = ({ row }) => {
  return row.maxScore >= 100 ? 'disabled-row' : ''
}

// 显示作业详情信息
const showDetail = (row) => {
  ElNotification({
    title: row.homeWorkName,
    duration: 3000,
    message: `
      <div class="detail-content">
        <p>🗓 截止日期: ${row.endTime || '未设置'}</p>
        <p>📝 作业类型: ${row.type || '常规练习'}</p>
        <p>🎯 当前分数: ${row.maxScore} 分</p>
        ${row.answerCount ? `<p>📚 已作答 ${row.answerCount} 次</p>` : ''}
      </div>
    `,
    dangerouslyUseHTMLString: true,
    customClass: 'detail-notification'
  })
}
</script>

<style scoped>
.processor-container {
  padding: 18px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 3px 8px rgba(0,0,0,0.08);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.process-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.hint-text {
  font-size: 13px;
  color: #606266;
  margin-left: 8px;
}

.table-header {
  font-weight: 600;
  color: #409eff;
}

.score-tag {
  font-weight: bold;
  min-width: 70px;
  justify-content: center;
  letter-spacing: 0.5px;
}

.status-text {
  margin-left: 6px;
  font-size: 13px;
}

.detail-content p {
  margin: 6px 0;
  color: #666;
}

:deep(.disabled-row) {
  opacity: 0.6;
  background-color: #fafafa;
  
  td {
    cursor: not-allowed;
    
    .el-checkbox {
      &__inner {
        background-color: #f5f7fa;
        border-color: #e4e7ed;
      }
      &.is-disabled {
        cursor: not-allowed;
      }
    }
  }
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  
  :deep(th.el-table__cell) {
    background-color: #f8f9fa;
  }
}
</style>